package com.yunmang.activity.ordermanager;

import android.graphics.Color;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.adapter.OrderManagerAdapter;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.ParameterEntity.OrderLookBean;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.DateUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/5/8.
 */
public class OrderManagerActivity extends BaseActivity {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.orderListview)
    ListView orderListview;
    @InjectView(R.id.ll_start)
    LinearLayout llStart;
    @InjectView(R.id.ll_container)
    LinearLayout ll_container;
    @InjectView(R.id.ll_endstart)
    LinearLayout llEndstart;
    @InjectView(R.id.start_date)
    TextView tvstartDate;
    @InjectView(R.id.tv_end_date)
    TextView tvEndDate;
    @InjectView(R.id.et_search)
    EditText etSearch;
    @InjectView(R.id.springView)
    SpringView springView;
    private OrderManagerAdapter adapter;
    private Subscriber<OrderLookBean> subscriber;
    private List<OrderLookBean.ModelBean.ItemsBean> dataList;
    private TimePickerView pvCustomTime,pvendTime;
    private int curPage;
    private int totalPages;
    @Override
    public int getLayoutId() {
        return R.layout.activity_order_manager;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        initToolbar();

    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        ll_container.setVisibility(View.VISIBLE);
    }
    @Override
    public void initData() {
        initCustomTimePicker();
        tvstartDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));
        tvEndDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));

        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                curPage = 0;
                requestData();
            }
            @Override
            public void onLoadmore() {
                if (curPage == totalPages)
                    springView.onFinishFreshAndLoad();
                else
                    requestData();
            }
        });
        springView.setHeader(new DefaultHeader(this));
        springView.setFooter(new DefaultFooter(this));
        springView.setType(SpringView.Type.FOLLOW);
    }

    @OnClick(R.id.btn_search)
    public void onClick() {
        requestData();
    }

    private void requestData(){
        String start = CommonUtils.getTextViewValue(tvstartDate);
        String end = CommonUtils.getTextViewValue(tvEndDate);
        String hdbh=CommonUtils.getTextViewValue(etSearch);
        int result = end.compareTo(start);
        if (result < 0) {
            showToast("结束日期不能小于开始日期");
            return;
        }
        showWaitingDialog("查询中……");
        getOrderInfo(start,end,hdbh);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void getOrderInfo(String start, String end, String hdbh) {
        subscriber = new Subscriber<OrderLookBean>() {
            @Override
            public void onCompleted() {
                springView.onFinishFreshAndLoad();
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
            }

            @Override
            public void onNext(OrderLookBean orderLookBean) {
                hideWaitingDialog();
                if(orderLookBean.getCode()==200){
                    dataList=orderLookBean.getModel().getItems();
                    if(dataList.size()==0){
                        showToast("暂无数据");
                        return;
                    }
                    orderListview.setAdapter(new OrderManagerAdapter(context,dataList));
                }else{
                    showToast(orderLookBean.getMessage());
                }
            }
        };
        HttpUtils.getInstance().orderLook(subscriber, start, end, AppConstant.userid,hdbh);
    }

    private void initCustomTimePicker() {

        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        final Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tvstartDate.setText(getTime(date));
                pvCustomTime.dismiss();
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.RED)
                .build();


        //时间选择器 ，自定义布局
        pvendTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tvEndDate.setText(getTime(date));
                pvendTime.dismiss();
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvendTime.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvendTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.RED)
                .build();

    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public void onEventMainThread(String event) {
        String start = CommonUtils.getTextViewValue(tvstartDate);
        String end = CommonUtils.getTextViewValue(tvEndDate);
        String hdbh=CommonUtils.getTextViewValue(etSearch);
        int result = end.compareTo(start);
        showWaitingDialog("查询中……");
        getOrderInfo(start,end,hdbh);
    }

    @OnClick({R.id.ll_start, R.id.ll_endstart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_start:
                pvCustomTime.show();
                break;
            case R.id.ll_endstart:
                pvendTime.show();
                break;
        }
    }

}
